package xyz.penghaonan.adtools.manager;

import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;

import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.LoadAdError;
import com.penghaonan.appframework.AppDelegate;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import xyz.penghaonan.adtools.ADLog;
import xyz.penghaonan.adtools.ADTools;

public class AdViewLoader {

    @WorkerThread
    public ADTools.AdLoadResult loadAdView(Context context, AdSpotInfo spotInfo) {
        ADTools.AdLoadResult result = new ADTools.AdLoadResult();
        for (AdSpotInfo.AdInfo adInfo : spotInfo.adList) {
            if (AdSpotInfo.AdInfo.TYPE_ADMOB.equals(adInfo.type)) {
                View view = loadAdmobView(context, adInfo);
                if (view != null) {
                    result.adView = view;
                    break;
                }
            } else if (AdSpotInfo.AdInfo.TYPE_AUDIENCE.equals(adInfo.type)) {
                View view = loadAudienceView(context, adInfo);
                if (view != null) {
                    result.adView = view;
                    break;
                }
            }
        }
        result.failMsg = "No available ad info";
        return result;
    }

    private View loadAdmobView(Context context, AdSpotInfo.AdInfo adInfo) {
        AtomicBoolean loaded = new AtomicBoolean(false);
        final CountDownLatch latch = new CountDownLatch(1);
        AdView adView = new AdView(context);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                super.onAdClosed();
                ADLog.i("onAdClosed");
            }

            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                ADLog.i("onAdFailedToLoad, " + loadAdError.toString());
                latch.countDown();
            }

            @Override
            public void onAdOpened() {
                super.onAdOpened();
                ADLog.i("onAdOpened");
            }

            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                ADLog.i("onAdLoaded");
                loaded.set(true);
                latch.countDown();
            }

            @Override
            public void onAdClicked() {
                super.onAdClicked();
                ADLog.i("onAdClicked");
            }

            @Override
            public void onAdImpression() {
                super.onAdImpression();
                ADLog.i("onAdImpression");
            }
        });
        adView.setAdUnitId(adInfo.adId);
        AppDelegate.post(new Runnable() {
            @Override
            public void run() {
                adView.loadAd(new AdRequest.Builder().build());
            }
        });
        try {
            latch.await(ADTools.getAdConfig().ad_request_timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (loaded.get()) {
            return adView;
        } else {
            return null;
        }
    }

    private View loadAudienceView(Context context, AdSpotInfo.AdInfo adInfo) {
        AtomicBoolean loaded = new AtomicBoolean(false);
        com.facebook.ads.AdView adView = new com.facebook.ads.AdView(context, adInfo.adId, com.facebook.ads.AdSize.BANNER_HEIGHT_50);
        adView.loadAd(adView.buildLoadAdConfig().withAdListener(new com.facebook.ads.AdListener() {
            @Override
            public void onError(Ad ad, AdError adError) {
                loaded.notify();
            }

            @Override
            public void onAdLoaded(Ad ad) {
                loaded.set(true);
                loaded.notify();
            }

            @Override
            public void onAdClicked(Ad ad) {

            }

            @Override
            public void onLoggingImpression(Ad ad) {

            }
        }).build());
        try {
            loaded.wait(ADTools.getAdConfig().ad_request_timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (loaded.get()) {
            return adView;
        } else {
            return null;
        }
    }
}
